package com.weilele.leisure.time.ui.module.video_detail


import android.os.Bundle
import android.view.View
import androidx.fragment.app.Fragment
import com.weilele.base.library.BaseBindingFragment
import com.weilele.base.library.FragmentContainerActivity
import com.weilele.base.library.SwitchView
import com.weilele.leisure.time.R
import com.weilele.leisure.time.bean.VideoDetailBean
import com.weilele.leisure.time.bean.VideoListBean
import com.weilele.leisure.time.bean.db.CommonDb
import com.weilele.leisure.time.databinding.FragmentVideoDetailBinding
import com.weilele.leisure.time.ui.player.VideoModel
import com.weilele.mvvm.base.helper.createViewModel
import com.weilele.mvvm.base.livedata.*
import com.weilele.mvvm.utils.activity.*
import com.weilele.mvvm.utils.formJsonString
import com.weilele.mvvm.utils.getCountTimeByLong
import com.weilele.mvvm.utils.toJsonString
import com.weilele.mvvm.utils.view_page.simplePagerAdapter
import com.weilele.leisure.time.bean.db.HistoryVideoBean
import com.weilele.leisure.time.ui.dialog.CacheListDialog
import com.yizisu.playerlibrary.helper.SimplePlayerListener

class VideoDetailFragment : BaseBindingFragment<FragmentVideoDetailBinding>(),
    SimplePlayerListener<VideoModel> {
    companion object {
        private const val KEY_VIDEO = "KEY_VIDEO"
        fun start(view: View, video: VideoListBean.RowsDTO?) {
            val appCompatActivity = view.getActivity() ?: return
            FragmentContainerActivity.start<VideoDetailFragment>(
                appCompatActivity,
                bundle = Bundle().also {
                    it.putString(KEY_VIDEO, video?.toJsonString())
                })
        }

        fun start(fg: Fragment, video: HistoryVideoBean?) {
            val appCompatActivity = fg.appCompatActivity ?: return
            FragmentContainerActivity.start<VideoDetailFragment>(
                appCompatActivity,
                bundle = Bundle().also {
                    val bean = VideoListBean.RowsDTO()
                    bean.id = video?.videoId ?: 0
                    bean.title = video?.title
                    it.putString(KEY_VIDEO, bean.toJsonString())
                })
        }
    }

    private val videoDetailViewModel: VideoDetailViewModel by lazy { createViewModel() }

    private val videoInfo by lazy {
        arguments?.getString(KEY_VIDEO)?.formJsonString<VideoListBean.RowsDTO>()
    }


    override fun initUi(savedInstanceState: Bundle?) {
        super.initUi(savedInstanceState)
        appCompatActivity?.window?.statusBarColor = getResColor(android.R.color.black)
        appCompatActivity?.isStatusBarBlackTextColor(false)
        videoDetailViewModel.playerHelperData.success(VideoDetailPlayerHelper().apply {
            lifecycle.addObserver(this)
            this.player.addPlayerListener(this@VideoDetailFragment)
        })
    }

    override fun initData() {
        super.initData()
        videoInfo?.let {
            videoDetailViewModel.getVideoDetail(it)
        }
    }

    override fun getObserverLiveData(): List<LiveDataWrap>? {
        return listOf(
            videoDetailViewModel.videoDetailData wrapObserver ::onVideoDetail,
            videoDetailViewModel.playListChangeData wrapSuccessObserver ::onPlayListChange,
        )
    }

    fun showCacheDialog(view: View) {
        val videos = videoDetailViewModel.videoDetailData.data ?: return
        if (videos.players.isNullOrEmpty()) {
            R.string.no_play_url.toast()
            return
        }
        val currentItem = mBinding.viewPager2.currentItem
        val playersDTO = videos.players[currentItem]
        val playersDatas = playersDTO.datas
        CacheListDialog.show(
            view,
            playersDatas,
            playersDTO,
            videos
        )
    }

    /**
     * 视频详情回调
     */
    private fun onVideoDetail(value: StatusData<VideoDetailBean>?) {
        when (value?.status) {
            StatusData.Error -> {
                showContentView()
            }
            StatusData.Running -> {
                showLoadingView(SwitchView.LoadingBean("正在加载视频详情"))
            }
            StatusData.Success -> {
                showContentView()
                showUi(value.data)
            }
        }
    }

    /**
     * 播放列表发送变化
     */
    private fun onPlayListChange(bean: Pair<String?, Int>?) {
        hideContinueSeeBt()
        mBinding.viewPager2.adapter?.notifyDataSetChanged()
    }

    override fun onPlayerModelChange(playerModel: VideoModel) {
        super.onPlayerModelChange(playerModel)
        //这里主要针对，点击上一首，下一首，列表无法改变
        videoDetailViewModel.playListChangeData.data?.let {
            val currentIndex =
                videoDetailViewModel.playerHelperData.data?.player?.getCurrentPlayIndex() ?: 0
            if (it.second != currentIndex) {
                videoDetailViewModel.playListChangeData.success(Pair(it.first, currentIndex))
            }
        }
    }

    override fun isNeedSwitchView(): Boolean {
        return true
    }

    private fun showUi(value: VideoDetailBean?) {
        value ?: return
        mBinding.layoutDetail.visible()
        checkHistory(value)
        //设置播放链接
        initViewPager(value)
    }

    /**
     * 检查时候有播放历史
     */
    private val historyData by lazy { CommonDb.getHistoryPlayVideos() }
    private fun checkHistory(value: VideoDetailBean?) {
        value ?: return
        var historyBean: HistoryVideoBean? = null
        //上次播放的对象集合
        var lastPlayList: VideoDetailBean.PlayersDTO? = null
        //上次播放的链接
        var lastPlayUrl: VideoDetailBean.PlayersDTO.DatasDTO? = null
        historyData.forEach History@{ h ->
            if (h.videoId == value.id) {
                value.players?.forEach { list ->
                    lastPlayList = list
                    if (list.key == h.listKey) {
                        list.datas?.forEach {
                            if (it.playUrl == h.playUrl) {
                                historyBean = h
                                lastPlayUrl = it
                                return@History
                            }
                        }
                    }
                }
            }
        }
        val history = historyBean
        val playList = lastPlayList
        val playUrl = lastPlayUrl
        if (history == null || playList == null || playUrl == null) {
            mBinding.llHistory.gone()
        } else {
            mBinding.llHistory.visible()
            mBinding.tvHistory.textFrom(
                "上次播放：${playUrl.text}" +
                        "(${getCountTimeByLong(history.currentDuration)}/${
                            getCountTimeByLong(
                                history.totalDuration
                            )
                        })\n播放来源：${playList.name}  "
            )
            mBinding.tvContinueSee.onClick {
                //继续历史播放
                videoDetailViewModel.startPlay(
                    value,
                    playList,
                    playList.datas,
                    playList.datas.indexOf(playUrl),
                    history.currentDuration
                )
                //跳转到对应界面
                mBinding.viewPager2.setCurrentItem(value.players.indexOf(playList), false)
            }
        }
    }

    private fun hideContinueSeeBt() {
        mBinding.llHistory.gone()
    }


    /**
     * 设置viewpager
     */
    private fun initViewPager(value: VideoDetailBean) {
        val datas = value.players?.toMutableList() ?: mutableListOf()
        value.players?.forEach {
            if (it.datas.isNullOrEmpty()) {
                datas.remove(it)
            }
        }
        if (datas.isEmpty()) {
            mBinding.tvNoUrl.visible()
            mBinding.viewPager2.gone()
            mBinding.tabLayout.gone()
        } else {
            mBinding.tvNoUrl.gone()
            mBinding.viewPager2.visible()
            mBinding.tabLayout.visible()
            mBinding.viewPager2.simplePagerAdapter(this, datas) { position, playersDTO ->
                PlayListFragment.newInstance(position)
            }
            mBinding.tabLayout.attachViewPager2(mBinding.viewPager2) { tab, position ->
                tab.text = datas[position].name
            }
        }
    }
}